package com.example.demo.services.admin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.example.demo.models.admin.*;
import gaarason.database.appointment.OrderBy;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;

import java.util.*;

public class AdminService {
    private static Admin.Model adminModel;
    private static Role.Model roleModel;
    private static Permission.Model permissionModel;

    private static AdminRole.Model adminRoleModel;
    private static RolePermission.Model rolePermissionModel;

    static {
        adminModel = SpringUtil.getBean(Admin.Model.class);
        roleModel = SpringUtil.getBean(Role.Model.class);
        permissionModel = SpringUtil.getBean(Permission.Model.class);
        adminRoleModel = SpringUtil.getBean(AdminRole.Model.class);
        rolePermissionModel = SpringUtil.getBean(RolePermission.Model.class);
    }

//    public static void main(String[] args) {
//        String pPath = "get /admin*change*";
//        String method = "GET";
//        String path = "/admin/change";
//        System.out.println(checkMethodAndPath(pPath, method, path));
//    }

    private static boolean checkMethodAndPath(String data, String method, String path) {
        //根据空格进行切分
        String[] dataArray = data.split(" ");
        if (dataArray.length >= 2) {
            //超过2个才可被使用
            String pMethod = dataArray[0];//第一个是参数
            String pPath = dataArray[1];//第二个是路径
            if (pMethod.equals("ANY") || (StrUtil.equalsAnyIgnoreCase(pMethod, "GET") && StrUtil.equalsAnyIgnoreCase(pMethod, method)) || (StrUtil.equalsAnyIgnoreCase(pMethod, "POST") && StrUtil.equalsAnyIgnoreCase(pMethod, method))) {
//                System.out.println("method ok");
                //如果记录的Method是ANY，则不管。
                //否则判断是GET还是POST


                //匹配路径的*号
                if (!pPath.contains("*")) {
//                    System.out.println("contains ok");
                    //如果找不到*，代表完整匹配
                    if (pPath.equals(path)) {
                        return true;
                    }
                } else {
                    //根据*号的位置切开成两块
                    String start = StrUtil.subBefore(pPath, "*", false);
                    String end = StrUtil.subAfter(pPath, "*", false);
//                    System.out.println("not contain");
//                    System.out.println("start:" + start);
//                    System.out.println("end:" + end);
//                    System.out.println("startwith:" + StrUtil.startWith(path, start));
//                    System.out.println("endwith:" + StrUtil.endWith(path, end));
                    if (StrUtil.startWith(path, start) && StrUtil.endWith(path, end)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static boolean checkAdminHasPermissionUrl(Admin admin, String method, String path) {
        //获得所有权限
        List<String> permissionIdList = AdminRolePermissionService.getAdminPermission(admin);
        for (String id : permissionIdList) {
            Record<Permission, Long> permission = permissionModel.newQuery().find(id);
            if (permission != null) {
                //permission存在

                if (checkMethodAndPath(permission.getEntity().getData(), method, path)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查管理员是否有某个权限
     *
     * @param admin
     * @param permissionName
     * @return
     */
    public static boolean checkAdminHasPermission(Admin admin, String permissionName) {
        Record<Permission, Long> permission = permissionModel.newQuery().where("name", permissionName).first();
        if (permission != null) {
            return checkAdminHasPermission(admin, permission.getEntity());
        } else {
            return false;
        }
    }

    /**
     * 检查管理员是否有某个权限
     *
     * @param admin
     * @param permission
     * @return
     */
    public static boolean checkAdminHasPermission(Admin admin, Permission permission) {
        List<String> permissionIdList = AdminRolePermissionService.getAdminPermission(admin);
        for (String pId : permissionIdList) {
            if (pId.equals(String.valueOf(permission.getId()))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获得管理员所有角色，含未配置的
     *
     * @param admin
     * @return
     */
    public static List<Map<String, String>> getAdminExistRole(Admin admin) {
        List<String> existRole = AdminRolePermissionService.getAdminRole(admin);
        //获得所有角色
        // RecordList<Role, Long> list = roleModel.newQuery().where("id", existRole).orderBy("id", OrderBy.ASC).get();
        RecordList<Role, Long> list = roleModel.newQuery().orderBy("id", OrderBy.ASC).get();
        List<Map<String, String>> role = new ArrayList<>();
        for (Record<Role, Long> roleRecord : list) {
            Role tempRole = roleRecord.getEntity();
            if (existRole.contains(String.valueOf(tempRole.getId()))) {
                Map<String, String> temp = new LinkedHashMap<>();
                temp.put("id", String.valueOf(tempRole.getId()));
                temp.put("name", String.valueOf(tempRole.getName()));
                temp.put("description", String.valueOf(tempRole.getDescription()));
                role.add(temp);
            }
        }
        return role;
    }

    /**
     * 获得管理员所有角色，含未配置的
     *
     * @param admin
     * @return
     */
    public static List<Map<String, String>> getAdminRole(Admin admin) {
        List<String> existRole = AdminRolePermissionService.getAdminRole(admin);
        //获得所有角色
        RecordList<Role, Long> list = roleModel.newQuery().orderBy("id", OrderBy.ASC).get();
        List<Map<String, String>> role = new ArrayList<>();
        for (Record<Role, Long> roleRecord : list) {
            Map<String, String> temp = new LinkedHashMap<>();
            Role tempRole = roleRecord.getEntity();
            temp.put("id", String.valueOf(tempRole.getId()));
            temp.put("name", String.valueOf(tempRole.getName()));
            temp.put("description", String.valueOf(tempRole.getDescription()));
            if (existRole.contains(String.valueOf(tempRole.getId()))) {
                temp.put("checked", "true");
            } else {
                temp.put("checked", "false");
            }
            role.add(temp);
        }
        return role;
    }

    /**
     * 获得角色所有权限，含未配置的
     *
     * @param role
     * @return
     */
    public static List<Map<String, String>> getRolePermission(Role role) {
        List<String> existPermission = AdminRolePermissionService.getRolePermission(role);
        //获得所有角色
        RecordList<Permission, Long> list = permissionModel.newQuery().orderBy("id", OrderBy.ASC).get();
        List<Map<String, String>> permission = new ArrayList<>();
        for (Record<Permission, Long> permissionRecord : list) {
            Map<String, String> temp = new LinkedHashMap<>();
            Permission tempRole = permissionRecord.getEntity();
            temp.put("id", String.valueOf(tempRole.getId()));
            temp.put("name", String.valueOf(tempRole.getName()));
            temp.put("description", String.valueOf(tempRole.getDescription()));
            if (existPermission.contains(String.valueOf(tempRole.getId()))) {
                temp.put("checked", "true");
            } else {
                temp.put("checked", "false");
            }
            permission.add(temp);
        }
        return permission;
    }
}
